<?php
/**
 * +----------------------------------------------------------------------
 * | summer framework
 * +----------------------------------------------------------------------
 * | Copyright (c) 2020 https://github.com/suframe/think-admin All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: summer <806115620@qq.com>  2020/3/26 10:40
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\mall\logic;

use app\mall\Events;
use app\mall\exceptions\GoodsException;
use app\mall\model\MallGoods;
use app\mall\model\MallGoodsStock;
use app\mall\model\MallStore;
use app\mall\model\MallStoreGoods;

/**
 * 公共库商品service
 * Class GoodsService
 * @package app\mall\service
 */
class GoodsLogic extends Base
{
    /**
     * 创建商品
     * @param array $info
     * @return int
     */
    public function create(array $info): int
    {
        //检测去重
        //增加到数据库
    }

    /**
     * 修改信息
     * @param MallGoods $mallGoods
     * @param array $info
     * @return bool
     */
    public function edit(MallGoods $mallGoods, array $info): bool
    {

    }

    /**
     * 商品检索
     * @param $cond
     * @return array
     */
    public function search($cond): array
    {
        return [];
    }

    /**
     * 根据id条件检索
     * @param int $id
     * @param array $cond
     * @return MallGoods
     */
    public function findById(int $id, array $cond = []): MallGoods
    {
    }

    /**
     * 根据条件查找
     * @param $cond
     * @return MallGoods
     */
    public function find($cond): MallGoods
    {

    }

    /**
     * 下架
     * @param MallGoods $mallGoods
     * @return bool
     */
    public function down(MallGoods $mallGoods): bool
    {

    }

    /**
     * 上架
     * @param MallGoods $mallGoods
     * @return bool
     */
    public function up(MallGoods $mallGoods): bool
    {

    }

    /**
     * 商品单个属性库存更新
     * @param MallGoodsStock $mallGoodsStock
     * @param int $num
     * @param string $reason
     * @return bool
     * @throws \app\mall\exceptions\BaseException
     */
    public function updateStock(MallGoodsStock $mallGoodsStock, int $num, string $reason = ''): bool
    {
        if (!$mallGoodsStock->isEnough($num)) {
            GoodsException::throws(GoodsException::$outOffStock);
        }
        $mallGoodsStock->stock += $num;
        $rs = $mallGoodsStock->save();
        if (!$rs) {
            GoodsException::throws(GoodsException::$errorStock);
        }
        event(
            $num > 0 ? Events::GOODS_STOCK_INC : Events::GOODS_STOCK_DESC,
            [
                'stock' => $mallGoodsStock,
                'num' => $num,
                'reason' => $reason,
            ]
        );
        return $rs;
    }

}